﻿package net.wangit.jdbc.sqltype;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;

import net.wangit.jdbc.JDBCException;


public class TextSqlType extends NullableSqlType {

	private static final long serialVersionUID = 1L;

	public TextSqlType() {
	}

	public String get(ResultSet rs, String name) throws SQLException,
			JDBCException {
		Reader charReader;
		StringBuffer sb;
		charReader = rs.getCharacterStream(name);
		if (charReader == null)
			return null;
		sb = new StringBuffer();
		try {
			char buffer[] = new char[2048];
			do {
				int amountRead = charReader.read(buffer, 0, buffer.length);
				if (amountRead == -1)
					break;
				sb.append(buffer, 0, amountRead);
			} while (true);
		} catch (IOException ioe) {
			throw new JDBCException("IOException occurred reading text", ioe);
		} finally {
			try {
				charReader.close();
			} catch (IOException e) {
				throw new JDBCException("IOException occurred closing stream",
						e);
			}
		}
		return sb.toString();
	}

	public void setNotNull(PreparedStatement st, String value, int index)
			throws SQLException {
		String str = value;
		st.setCharacterStream(index, new StringReader(str), str.length());
	}

	public int sqlType() {
		return Types.CLOB;
	}
}
